package edu.bit.water.service;

import com.alibaba.fastjson.JSON;
import edu.bit.water.dao.MetaEffluentLetAssociationDao;
import edu.bit.water.dao.MetaEffluentLetDao;
import edu.bit.water.entity.MetaEffluentLet;
import edu.bit.water.entity.MetaSensor;
import edu.bit.water.view.BasicResult;
import edu.bit.water.view.ResultState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 废水排放元数据表的Service层
 * @author HuJishuang
 * @date 19.07.07
 */

@Service
public class MetaEffluentLetService {

    @Autowired
    private MetaEffluentLetDao metaEffluentLetDao;
    @Autowired
    private MetaEffluentLetAssociationDao metaEffluentLetAssociationDao;

    public String insert(MetaEffluentLet metaEffluentLet) {
        BasicResult result = new BasicResult();
        String message = "";
        MetaEffluentLet enNameResult = metaEffluentLetDao.selectByEnName(metaEffluentLet.getEnName());
        MetaEffluentLet csNameResult = metaEffluentLetDao.selectByCsName(metaEffluentLet.getCsName());
        if (enNameResult != null && csNameResult != null) {
            message = "中文名称和英文名称已存在";
            result.setCode(ResultState.FAILURE.code);
        } else if (enNameResult != null) {
            message = "英文名称已存在";
            result.setCode(ResultState.FAILURE.code);
        }
        else if (csNameResult != null) {
            message = "中文名称已存在";
            result.setCode(ResultState.FAILURE.code);
        } else if (enNameResult == null && csNameResult == null) {
            metaEffluentLetDao.insert(metaEffluentLet);
            metaEffluentLetAssociationDao.insertMetaEffluentLetAssociation(metaEffluentLet.getEnName());
            result.setCode(ResultState.SUCCESS.code);
        }
        return JSON.toJSONString(result.setMessage(message));
    }

    public String delete(List<String> enNameList) {
        for (String enName : enNameList) {
            metaEffluentLetDao.delete(enName);
            metaEffluentLetAssociationDao.deleteMetaEffluentLetAssociation(enName);
        }
        return JSON.toJSONString(new BasicResult(ResultState.SUCCESS.code, null, null));
    }

    public String selectAll() {
        List<MetaEffluentLet> list = metaEffluentLetDao.selectAll();
        return JSON.toJSONString(new BasicResult(ResultState.SUCCESS.code, list, null));
    }
    public Map<String, Object> updateMetaEffluentLet(MetaEffluentLet MetaEffluentLet) {
        Map<String, Object> result = new HashMap<>();
        int tmp = metaEffluentLetAssociationDao.updateMetaEffluentLetAssociation(MetaEffluentLet);
        if(tmp == 1) {
            result.put("status", "success");
        }
        else {
            result.put("status", "failed");
        }
        return result;
    }
}
